"""
文档解析工具
支持多种文档格式：docx, doc, pdf, md, csv, xlsx, xls
"""
import os
from typing import Optional


def parse_document(file_path: str, file_type: str) -> Optional[str]:
    """
    解析文档内容
    
    Args:
        file_path: 文件路径
        file_type: 文件类型
        
    Returns:
        解析后的文本内容
    """
    if not file_type:
        raise ValueError("文件类型为空，请确保文件有正确的扩展名")
    
    if file_type in ['docx', 'doc']:
        return parse_word(file_path)
    elif file_type == 'pdf':
        return parse_pdf(file_path)
    elif file_type in ['md', 'txt']:
        return parse_text(file_path)
    elif file_type in ['xlsx', 'xls', 'csv']:
        return parse_excel(file_path, file_type)
    else:
        raise ValueError(f"不支持的文件类型: {file_type}。支持的格式: docx, doc, pdf, txt, md, csv, xlsx, xls")


def parse_word(file_path: str) -> str:
    """解析Word文档（支持中文）"""
    try:
        from docx import Document
        doc = Document(file_path)
        
        # 提取所有段落
        paragraphs = []
        for para in doc.paragraphs:
            text = para.text.strip()
            if text:
                # 确保中文正确处理
                paragraphs.append(text)
        
        # 提取表格内容
        for table in doc.tables:
            for row in table.rows:
                row_data = []
                for cell in row.cells:
                    cell_text = cell.text.strip()
                    if cell_text:
                        row_data.append(cell_text)
                if row_data:
                    paragraphs.append(' | '.join(row_data))
        
        content = '\n'.join(paragraphs)
        
        # 确保返回的内容是有效的UTF-8字符串
        if content:
            return content
        else:
            return "文档内容为空"
            
    except ImportError:
        raise ImportError("需要安装 python-docx: pip install python-docx")
    except Exception as e:
        raise Exception(f"Word文档解析失败: {e}")


def parse_pdf(file_path: str) -> str:
    """解析PDF文档"""
    try:
        import PyPDF2
        
        text_content = []
        with open(file_path, 'rb') as file:
            pdf_reader = PyPDF2.PdfReader(file)
            
            for page_num in range(len(pdf_reader.pages)):
                page = pdf_reader.pages[page_num]
                text = page.extract_text()
                if text and text.strip():
                    # 处理PDF中的中文编码问题
                    text_content.append(text.strip())
        
        result = '\n'.join(text_content)
        
        # 如果内容为空或只有空白字符，尝试使用其他方法
        if not result.strip():
            # 尝试使用 pdfplumber（如果可用）
            try:
                import pdfplumber
                with pdfplumber.open(file_path) as pdf:
                    for page in pdf.pages:
                        text = page.extract_text()
                        if text:
                            text_content.append(text.strip())
                result = '\n'.join(text_content)
            except ImportError:
                pass  # pdfplumber 不可用，使用 PyPDF2 的结果
        
        return result
    except ImportError as e:
        if 'PyPDF2' in str(e):
            raise ImportError("需要安装 PyPDF2: pip install PyPDF2")
        raise e
    except Exception as e:
        raise Exception(f"PDF文档解析失败: {e}")


def parse_text(file_path: str) -> str:
    """解析文本文件（txt, md）- 支持多种中文编码"""
    try:
        # 尝试多种编码，包括常见的中文编码
        encodings = ['utf-8', 'utf-8-sig', 'gbk', 'gb2312', 'gb18030', 'big5', 'utf-16', 'utf-16-le', 'utf-16-be']
        
        last_error = None
        for encoding in encodings:
            try:
                with open(file_path, 'r', encoding=encoding, errors='ignore') as file:
                    content = file.read()
                    # 如果成功读取且内容不为空，返回
                    if content and content.strip():
                        return content
            except (UnicodeDecodeError, LookupError) as e:
                last_error = e
                continue
        
        # 如果所有编码都失败，尝试二进制模式读取并尝试解码
        try:
            with open(file_path, 'rb') as file:
                raw_data = file.read()
                # 尝试检测编码
                for encoding in encodings:
                    try:
                        content = raw_data.decode(encoding, errors='ignore')
                        if content and content.strip():
                            return content
                    except:
                        continue
        except Exception as e:
            last_error = e
        
        raise Exception(f"无法识别文件编码。已尝试: {', '.join(encodings)}。最后错误: {last_error}")
    except Exception as e:
        raise Exception(f"文本文件解析失败: {e}")


def parse_excel(file_path: str, file_type: str) -> str:
    """解析Excel文件（支持中文）"""
    try:
        import pandas as pd
        
        if file_type == 'csv':
            # 尝试多种编码读取CSV，包括中文编码
            encodings = ['utf-8', 'utf-8-sig', 'gbk', 'gb2312', 'gb18030', 'big5']
            df = None
            last_error = None
            
            for encoding in encodings:
                try:
                    df = pd.read_csv(file_path, encoding=encoding)
                    break
                except (UnicodeDecodeError, LookupError) as e:
                    last_error = e
                    continue
            
            if df is None:
                raise Exception(f"无法识别CSV文件编码。已尝试: {', '.join(encodings)}。最后错误: {last_error}")
        else:
            # 读取Excel文件（pandas会自动处理中文）
            df = pd.read_excel(file_path, engine='openpyxl' if file_type == 'xlsx' else None)
        
        # 转换为文本格式
        text_lines = []
        
        # 添加列名
        text_lines.append(' | '.join(str(col) for col in df.columns))
        text_lines.append('-' * 50)
        
        # 添加数据行
        for _, row in df.iterrows():
            row_text = ' | '.join(str(val) if pd.notna(val) else '' for val in row.values)
            text_lines.append(row_text)
        
        return '\n'.join(text_lines)
    except ImportError as e:
        raise ImportError("需要安装 pandas 和 openpyxl: pip install pandas openpyxl")
    except Exception as e:
        raise Exception(f"Excel文件解析失败: {e}")


def get_file_type(filename: str) -> str:
    """从文件名获取文件类型"""
    return os.path.splitext(filename)[1].lower().replace('.', '')


def is_supported_file(filename: str) -> bool:
    """检查文件类型是否支持"""
    supported_types = ['docx', 'doc', 'pdf', 'md', 'txt', 'csv', 'xlsx', 'xls']
    file_type = get_file_type(filename)
    return file_type in supported_types

